package com.jaiai.work.util.redis.config;




import com.jaiai.work.util.redis.RedisUtil;
import com.jaiai.work.util.redis.properties.JedisProperties;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


@Configuration
@EnableConfigurationProperties(JedisProperties.class)//开启属性注入,通过@autowired注入
@ConditionalOnClass(RedisUtil.class)//判断这个类是否在classpath中存在
public class JedisAutoConfiguration {  
      
    @Autowired
    private JedisProperties prop;  
      
    @Bean(name="jedisPool")
    public JedisPool jedisPool() {  
        JedisPoolConfig config = new JedisPoolConfig();  
        config.setMaxTotal(prop.getMaxTotal());
		config.setMaxIdle(prop.getMaxIdle());
		config.setMinIdle(prop.getMinIdle());//设置最小空闲数
		config.setMaxWaitMillis(prop.getMaxWaitMillis());
		config.setTestOnBorrow(true);
		config.setTestOnReturn(true);
		//Idle时进行连接扫描
		config.setTestWhileIdle(true);
		//表示idle object evitor两次扫描之间要sleep的毫秒数
		config.setTimeBetweenEvictionRunsMillis(30000);
		//表示idle object evitor每次扫描的最多的对象数
		config.setNumTestsPerEvictionRun(10);
		//表示一个对象至少停留在idle状态的最短时间，然后才能被idle object evitor扫描并驱逐；这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义
		config.setMinEvictableIdleTimeMillis(60000);
		if(StringUtils.isEmpty(prop.getPassword()) ){
			return new JedisPool(config, prop.getHost(), prop.getPort(),prop.getTimeOut());  
		}
        return new JedisPool(config, prop.getHost(), prop.getPort(),prop.getTimeOut(),prop.getPassword());  
    }  
      
    @Bean(name = "rdisUtil")
    @ConditionalOnMissingBean(RedisUtil.class)//容器中如果没有RedisClient这个类,那么自动配置这个RedisClient
    public RedisUtil redisClient(@Qualifier("jedisPool")JedisPool pool) {
    	RedisUtil redisUtil = new RedisUtil(pool);  
        return redisUtil;  
    }  
      
}  